package com.yang.spring.core.bean.builder.post;

import com.yang.spring.core.bean.definition.BeanDefinition;
import com.yang.spring.core.bean.enums.BeanDefinitionExtendsEnum;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class BeanPostHandler {
    public void postHandleBeans(List<BeanDefinition> beanDefinitionList) {
        try {
            for (BeanDefinition beanDefinition : beanDefinitionList) {
                postConstructBean(beanDefinition);
                initializingBean(beanDefinition);
                initMethod(beanDefinition);
            }
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private void executePostMethod(BeanDefinition beanDefinition, BeanDefinitionExtendsEnum beanDefinitionExtendsEnum) throws InvocationTargetException, IllegalAccessException {
        Method initMethod = (Method) beanDefinition.getExtend(beanDefinitionExtendsEnum.getValue());
        if (initMethod == null) {
            return;
        }
        initMethod.setAccessible(true);
        Object instance = beanDefinition.getInstance();
        initMethod.invoke(instance);
    }

    private void initMethod(BeanDefinition beanDefinition) throws InvocationTargetException, IllegalAccessException {
        executePostMethod(beanDefinition, BeanDefinitionExtendsEnum.INIT_METHOD);
    }

    private void initializingBean(BeanDefinition beanDefinition) throws InvocationTargetException, IllegalAccessException {
        executePostMethod(beanDefinition, BeanDefinitionExtendsEnum.INITIALIZING_BEAN_METHOD);
    }

    public void postConstructBean(BeanDefinition beanDefinition) throws InvocationTargetException, IllegalAccessException {
        executePostMethod(beanDefinition, BeanDefinitionExtendsEnum.POST_CONSTRUCT_METHOD);
    }
}
